import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Card, Button, message, Badge, Tag } from 'antd';
import PateoTable from '../../../components/common/PateoTable';
import PateoSearchForm from '../../../components/common/PateoSearchForm';
import PateoAuthButtons from '../../../components/common/PateoAuthButtons';
import AddModal from './addModal';
import EditModal from './editModal';
import DetailModal from './detailModal';
import { filterAuth } from '@/support/common';
import PropTypes from 'prop-types';
import styles from '../../../components/common/PateoTable/TableList.less';
import { PlusOutlined } from '@ant-design/icons';
import moment from 'moment';
import * as G from '../../../utils/common';
import { handleExportExcel } from './variable';

const mapStateToProps = (state: any) => ({
  audienceList: state.audienceList,
  loading: state.loading.effects['audienceList/postFetchPage'],
  brandId:state?.menu?.brandId?.join(",") || ''
});
class AudienceList extends PureComponent<any, any> {
  static contextTypes = {
    // dicData: PropTypes.object,
    permissions: PropTypes.array,
  };

  constructor(props: any) {
    super(props);
    this.state = {
      formValues: {},
      disabled: false,
      detailData: '',
      addVisible: false,
      editVisible: false,
      detailVisible: false,
      vinFileUrl: '',
      filterUrl: null,
      recordObj: {},
    };
  }

  componentDidMount() {
    const { dispatch, location, history } = this.props;
    const bool = !!location.query?.history;
    const str = sessionStorage.getItem('audienceList') || '{}';
    const {
      addVisible,
      editVisible,
      vinFileUrl,
      filterUrl,
      page,
      size,
      formValues,
      recordObj,
    } = JSON.parse(str);

    dispatch({
      type: 'audienceList/postFetchPage',
      payload: { url: '/audience/group/page', ...formValues, page, size },
    });

    if (bool) {
      this.setState({
        addVisible,
        editVisible,
        vinFileUrl,
        filterUrl,
        formValues,
      });
      this.formRef.current.setFieldsValue(formValues);
      if (editVisible || addVisible) {
        const val = editVisible ? 'edit' : 'add';
        this[`${val}Form`].setData(recordObj);
      }
      history.replace(`${location.pathname}`);
      return false;
    }

    dispatch({
      type: 'audienceList/getData',
      payload: { url: '/audience/group/getBiToken' },
      callback: (res: any) => {
        this.setState({
          filterUrl: res.data
            ? `https://dftc-bi.dfiov.com.cn/?proc=1&action=viewer&hback=true&db=TSP!2f!!53d7!!4f17!!5bf9!!8c61!!62a5!!8868!.db&token=${res.data}`
            : null,
        });
      },
    });
    dispatch({
      type: 'audienceList/getData',
      payload: { url: '/common/template/detail', templateCode: 'audienceVin' },
      callback: (res: any) => {
        this.setState({ vinFileUrl: res.data ? res.data.templateUrl : null });
      },
    });
    sessionStorage.removeItem('audienceList');
  }

  componentWillUnmount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'audienceList/initData',
    });
  }

  handleFlushPage = () => {
    const {
      audienceList: {
        pageData: { pagination },
      },
      dispatch,
    } = this.props;
    const { current, pageSize } = pagination;
    const { formValues } = this.state;
    let params = { ...formValues, page: current, size: pageSize };
    dispatch({
      type: 'audienceList/postFetchPage',
      payload: { url: '/audience/group/page', ...params },
    });
  };

  handleAdd = () => {
    this.setState({
      addVisible: true,
    });
  };

  closeAddModal = () => {
    this.setState({
      addVisible: false,
    });
  };

  handleEdit = record => {
    this.getDetail(record, 'edit');
    // this.setState({
    //   editVisible: true,
    // });
    // this.editForm.setData(record);
  };

  closeEditModal = () => {
    this.setState({
      editVisible: false,
    });
  };

  handleDetail = record => {
    this.getDetail(record, 'detail');
  };
  getDetail = (record, val: string) => {
    const { dispatch } = this.props;
    // const val = 'detail';
    dispatch({
      type: 'audienceList/getData',
      payload: {
        url: `/audience/group/get/${record.sid}`,
      },
      callback: res => {
        const { statusCode, data } = res;
        if (statusCode === '0') {
          this.setState({
            [`${val}Visible`]: true,
          });
          this[`${val}Form`].setData({ ...record, list: data.classifyList });
        }
      },
    });
  };
  getInfoFn = (record, val: string) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'audienceList/postObjWithRes',
      payload: {
        url: `/upload/page`,
        // 受众对象组id
        objectGroupSid: record.sid,
        // 受众对象分类id
        objectClassifySid: null,
        // 页码
        page: null,
        // 每页数量
        size: null,
      },
      callback: (res: any) => {
        const { statusCode, data } = res;
        if (statusCode === '0') {
          this.setState({
            [`${val}Visible`]: true,
          });
          this[`${val}Form`].setData({ ...record, list: data.list });
        }
      },
    });
  };

  closeDetailModal = () => {
    this.setState({
      detailVisible: false,
    });
  };

  handleRefresh = () => {
    const {
      audienceList: {
        pageData: { pagination },
      },
      dispatch,
    } = this.props;
    const { current, pageSize } = pagination;
    const { formValues } = this.state;
    let params = { ...formValues, page: current, size: pageSize };
    dispatch({
      type: 'audienceList/postFetchPage',
      payload: { url: '/audience/group/page', ...params },
    });
  };

  handleNotice = () => {
    message.success('操作成功');
    this.handleRefresh();
  };

  handleNoticeDel = () => {
    message.success('删除成功');
    const {
      audienceList: {
        pageData: { pagination },
      },
      dispatch,
    } = this.props;
    const { current, pageSize } = pagination;
    const { formValues } = this.state;
    let params = { ...formValues, page: current, size: pageSize };
    dispatch({
      type: 'audienceList/postFetchPage',
      payload: { url: '/audience/group/page', ...params },
      callback: (response: any) => {
        if (!response.data.records || response.data.records.length === 0) {
          let obj = { ...formValues, page: current - 1 < 1 ? 1 : current - 1, size: pageSize };
          dispatch({
            type: 'audienceList/postFetchPage',
            payload: { url: '/audience/group/page', ...obj },
          });
        }
      },
    });
  };

  handleDelete = (sid: any) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'audienceList/putObjWithRes',
      payload: { url: `/audience/group/delete/${sid}` },
      callback: (response: any) => {
        if (response.statusCode === '0') {
          this.handleNoticeDel();
        }
      },
    });
  };

  dataFormat = (fields: any) => {
    if (G.isNotEmptyAndNil(fields['createDateRange'])) {
      const [start, end] = fields.createDateRange;
      fields['startTime'] = moment(start).format('YYYY-MM-DD HH:mm:ss');
      fields['endTime'] = moment(end).format('YYYY-MM-DD HH:mm:ss');
      delete fields['createDateRange'];
    }
    return fields;
  };

  filterClickFn = recordObj => {
    const { formValues, addVisible, editVisible, vinFileUrl, filterUrl } = this.state;
    const {
      history,
      location,
      audienceList: {
        pageData: { pagination },
      },
      brandId
    } = this.props;
    
    // 保存数据
    const { current, pageSize } = pagination;
    const str = JSON.stringify({
      addVisible,
      editVisible,
      vinFileUrl,
      filterUrl,
      page: current,
      size: pageSize,
      formValues,
      recordObj,
    });
    sessionStorage.setItem('audienceList', str);
    // 修改路由
    history.replace(`${location.pathname}?history=1`);
    // 跳转页面
    window.open(`${filterUrl}&brandid=${brandId}`, '_self');
  };

  render() {
    const {
      audienceList: {
        pageData: { list, pagination },
      },
      loading,
      location: { pathname = '/' },
    } = this.props;
    const { formValues, addVisible, editVisible, detailVisible } = this.state;
    const columns = [
      {
        title: '受众对象组编号',
        dataIndex: 'sid',
      },
      {
        title: '受众对象组名称',
        dataIndex: 'objectGroupName',
      },
      {
        title: '创建人',
        dataIndex: 'createBy',
      },
      {
        title: '创建时间',
        dataIndex: 'createTime',
        render: (text: any) => moment(text).format('YYYY-MM-DD HH:mm:ss'),
      },
      {
        title: '修改时间',
        dataIndex: 'updateTime',
        render: (text: any) => moment(text).format('YYYY-MM-DD HH:mm:ss'),
      },
      {
        title: '操作',
        dataIndex: '操作',
        width: 270,
        fixed: 'right',
        render: (text: any, record: any) => {
          const btns = [
            {
              title: '查看',
              key: 'detail',
              auth: 'audienceList_doDetail',
              onConfirm: () => this.handleDetail(record),
            },
            {
              title: '编辑',
              key: 'edit',
              auth: 'audienceList_doEdit',
              onConfirm: () => this.handleEdit(record),
            },
            {
              title: '删除',
              key: 'del',
              auth: 'audienceList_doDel',
              message: '是否确认删除？',
              Popconfirm: true,
              onConfirm: () => this.handleDelete(record.sid),
            },
            {
              title: '导出名单',
              key: 'export',
              // auth: 'audienceList_export',
              auth: 'audienceList_doDel',
              onConfirm: () => {
                handleExportExcel.call(this, record);
              },
            },
          ];
          return <PateoAuthButtons btns={btns} max={3} pathname={pathname} />;
        },
      },
    ];
    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      ...pagination,
      showTotal: () => (
        <span>共&nbsp;{pagination === undefined ? 0 : pagination.total}&nbsp;条</span>
      ),
    };
    const tableProps = {
      columns,
      dataSource: list,
      loading,
      rowKey: (record: any) => record.sid,
      pagination: paginationProps,
      scroll: { x: 'max-content' },
    };
    const searchItems = [
      {
        type: 'input',
        title: '受众对象组编号',
        key: 'sid',
      },
      {
        type: 'input',
        title: '受众对象组名称',
        key: 'objectGroupName',
      },
      {
        type: 'rangePicker',
        title: '创建起止时间',
        key: 'createDateRange',
      },
    ];
    return (
      <div>
        <Card bordered={false}>
          <PateoSearchForm
            onRef={(val: any) => (this.formRef = val)}
            searchItems={searchItems}
            fetchParams={{ type: 'audienceList/postFetchPage', url: '/audience/group/page' }}
            saveFormValues={(val: any) =>
              this.setState({ formValues: Object.assign(formValues, val) })
            }
            handleFieldsValue={this.dataFormat}
            handleFormReset={() => this.setState({ formValues: {} })}
          />
        </Card>
        <Card className={styles.standardTable}>
          {filterAuth('audienceList_doAdd', this.context.permissions, pathname) ? (
            <div className="my_newItem">
              <Button
                size="small"
                icon={<PlusOutlined />}
                type="primary"
                onClick={() => this.handleAdd()}
              >
                新增
              </Button>
            </div>
          ) : null}
          <PateoTable
            extraHandle={true}
            tableProps={tableProps}
            fetchParams={{ type: 'audienceList/postFetchPage', url: '/audience/group/page' }}
            formValues={formValues}
          />
        </Card>
        <AddModal
          onRef={(val: any) => (this.addForm = val)}
          modalVisible={addVisible}
          closeModal={this.closeAddModal}
          vinFileUrl={this.state.vinFileUrl}
          filterUrl={this.state.filterUrl}
          filterClickFn={this.filterClickFn}
        />
        <EditModal
          onRef={(val: any) => (this.editForm = val)}
          modalVisible={editVisible}
          closeModal={this.closeEditModal}
          formValues={formValues}
          vinFileUrl={this.state.vinFileUrl}
          filterUrl={this.state.filterUrl}
          filterClickFn={this.filterClickFn}
        />
        <DetailModal
          onRef={(val: any) => (this.detailForm = val)}
          modalVisible={detailVisible}
          closeModal={this.closeDetailModal}
          formValues={formValues}
        />
      </div>
    );
  }
}
export default connect(mapStateToProps)(AudienceList);
